package com.eland.oa.main.controller;

import java.util.HashMap;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import com.eland.oa.main.constant.ELOpCode;
import com.eland.oa.main.controller.util.ContextResolver;
import com.eland.oa.main.model.ELOpRtnPack;
import com.eland.oa.main.service.LoginDEPService;

@Controller
@RequestMapping("/login.htm")
public class LoginController {

	@Autowired @Qualifier("main-service-login")
	public LoginDEPService loginService;
	
	@RequestMapping(method= RequestMethod.GET)
	public ModelAndView loginHandler(@RequestParam(required=false) String contextCode, 
			@RequestParam(required=false) String redirect) {
		Map<String, Object> model = new HashMap<String, Object>();
		String contextMsg = null;
		
		//Check if there is a contextCode, default if void
		if (contextCode == null || contextCode.length() == 0) {
			contextCode = ELOpRtnPack.resolveReturnCode(
					ELOpCode.TYP_PLAIN, 
					ELOpCode.OP_SYS_LOGIN, 
					ELOpCode.MSG_LOGIN_P_WELCOME_TO_SYSTEM
					);
		}
		
		//Check if there is a redirect path, default if void
		if (redirect == null || redirect.length() == 0)
			redirect = "main.htm";
		
		//Check if the user is already logged in. If yes, redirect immediately
		if (loginService.isUserLoggedIn()) {
			return new ModelAndView("redirect:" + redirect);
		}
		
		//Resolve context message
		contextMsg = ELOpRtnPack.resolveReturnMessage(contextCode);
		
		//Set model attributes
		model.put("contextCode", contextCode);
		model.put("contextMsg", contextMsg);
		model.put("redirect", redirect);
		
		return new ModelAndView("login", "model", model);
	}
}
